package com.atguigu.yuntai.govern.parser;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.hadoop.hive.ql.parse.ASTNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 解析语法树，是否包含join
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JoinObj {

    ASTNode joinASTNode;

    String joinType; // LEFT,RIGHT,INNER

    List<TableObj> tableList = new ArrayList();

    List<JoinOnFieldPair> fieldPairList = new ArrayList<>();

    public JoinObj(String joinType, ASTNode joinASTNode) {
        this.joinType = joinType;
        handleJoin(joinASTNode);
    }

    private void handleJoin(ASTNode joinASTNode) {
        for (int i = 0; i < joinASTNode.getChildCount(); i++) {
            ASTNode node = (ASTNode) joinASTNode.getChild(i);
            if ("TOK_TABREF".equals(node.getText())) {
                tableList.add(new TableObj(node));
            } else if ("TOK_JOIN".equals(node.getText()) || "TOK_LEFTOUTERJOIN".equals(node.getText()) || "TOK_LEFTOUTERJOIN".equals(node.getText())) {
                handleSubJoinTable(node);
            } else if ("and".equals(node.getText())) {
                handleAnd(node);
            } else if ("=".equals(node.getText())) {
                handleEquality(node);
            }

        }
    }

    private void handleSubJoinTable(ASTNode joinASTNode) {
        for (int i = 0; i < joinASTNode.getChildCount(); i++) {
            ASTNode node = (ASTNode) joinASTNode.getChild(i);
            if ("TOK_TABREF".equals(node.getText())) {
                tableList.add(new TableObj(node));
            } else if ("TOK_JOIN".equals(node.getText()) || "TOK_LEFTOUTERJOIN".equals(node.getText()) || "TOK_LEFTOUTERJOIN".equals(node.getText())) {
                handleSubJoinTable(node);
            }

        }
    }

    private void handleEquality(ASTNode equalityTree) {
        FieldObj fieldObj1 = new FieldObj(equalityTree.getChild(0), tableList);
        FieldObj fieldObj2 = new FieldObj(equalityTree.getChild(1), tableList);
        fieldPairList.add(new JoinOnFieldPair(fieldObj1, fieldObj2));

    }

    private void handleAnd(ASTNode andNode) {
        for (int i = 0; i < andNode.getChildCount(); i++) {
            ASTNode subNode = (ASTNode) andNode.getChild(i);
            if ("=".equals(subNode.getText())) {
                handleEquality(subNode);
            }
        }
    }

}
